<?php
/**
 * Created by PhpStorm.
 * User:
 * Date: 15/9/9
 * Time: 下午4:06
 */
class LoginController extends BaseController {
    /*
      * @Author:      kc
     * @DateTime:    2017-02-22 14:30:32
     * @Description: 用户登录或注册
     * @link: http://www.activity.com/wechat/login?phone=13000000998&check_code=1234&register_source_id=10
     * */
    public function login()
    {
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required',
                'check_code' => 'required',
                'register_source_id' => 'required',
            )
        );
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $time_out_default = Config::get("user.check_code_time_out");
            //默认手机号固定验证码
            $cc = UserCheckCode::where('phone','13000000999')->first();
            if($cc){
                UserCheckCode::where('phone','13000000999')->update(array('check_code'=> '1234','out_time_at'=>Common::num2DateTime(time() + $time_out_default)));
            }else{
                //记录数据库
                $data = array(
                    'phone' => '13000000999',
                    'area' => '010',
                    'check_code' => '1234',
                    'created_at' => Common::num2DateTime(time()),
                    'out_time_at' => Common::num2DateTime(time() + $time_out_default),
                    'send_id' => 1,
                );
                try {
                    UserCheckCode::insCheckCode($data);
                } catch (Exception $e) {
                    Log::error("error", array("system" => "wechat2.0" ,"event" => "login_sms_check_code", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("error.user_sms_check_code_create_error_1002");
                    break;
                }
            }
            $area = '010';
            $record = UserCheckCode::getCheckCode(Input::get('phone'),$area);
            if (is_null($record)) { //没有记录
                $response = Lang::get("error.user_login_checkcode_null_10004");
                break;
            }
            //校验是否超过时限
            if (time() > Common::datetime2Num($record->out_time_at)) {
                $response = Lang::get("error.user_login_checkcode_timeout_10005");
                break;
            }
            //校验验证码是否正确
            if ($record->check_code != Input::get('check_code')) {
                $response = Lang::get("error.user_login_checkcode_error_10006");
                break;
            }
            $wechat = Users::getUser(Input::get('phone'));
            if (is_null($wechat)) {
                try{
                        $wechat = new Users();
                        $wechat->phone = Input::get('phone');
                        $wechat->status = 1;
                        $wechat->register_source_id = Input::get('register_source_id');//1-微站 2-app 14-门店
                        $wechat->real_name = '';
                        $wechat->sex = 0;
                        $wechat->area = '010';
                        $wechat->type = 1;
                        $wechat->activate = 1;
                        $wechat->nickname = '';
                        $wechat->heading_img = '';
                        $wechat->member = Config::get('user.def_member');
                        $wechat->save();

                        if(Config::get("config.register_coupons") == 1){
                            $activity = Coupons::getNewUserRegister(Config::get('config.activity_id'),$response);
                            if(!is_null($activity)){
                                foreach ($activity as  $v) {
                                    $coupon_base_info = Coupons::getCouponBaseInfo($v->coupon_base_info_id);
                                    if (!$coupon_base_info) {
                                        break;
                                    }
                                    if ($coupon_base_info->status == 0) {
                                        break;
                                    }
                                    if ($coupon_base_info->date_type == 0 && strtotime($coupon_base_info->end_date.' 23:59:59') < strtotime(date('Y-m-d H:i:s', time()))) { //起止时间
                                        break;
                                    }
                                    $coupon_whether_exist = Coupons::getCouponOther($v->coupon_base_info_id);
                                    if (!is_null($coupon_whether_exist)) {
                                        $coupons = Coupons::find($coupon_whether_exist->id);
                                        $coupons->status = 2;
                                        $coupons->received_user_id = $wechat->id;
                                        $coupons->get_time = date("Y-m-d H:i:s", time());
                                        if ($coupon_base_info->date_type == 1) { //顺延日期
                                            $coupons->end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
                                        }
                                        $coupons->save();

                                        //友盟优惠券到账消息推送
                                        if(Config::get('u_meng_push.is_open_u_meng_push') ==1 && Input::get('register_source_id') ==2){
                                            Orders::notifyMsg($wechat->id,2,'优惠券已到账','您的'.($coupon_base_info->amount/100).'元优惠券已到帐');
                                        }

                                        try {
                                            NewsLog::NewsPush($wechat->id,'',2,5,'优惠券已到账','您的'.($coupon_base_info->amount/100).'元优惠券已到帐');
                                        } catch (Exception $e) {
                                            Log::error("error", array("system" => "api3.0" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                                            $response = Lang::get("error.run_exception");
//                break;
                                        }
                                    }
                                }
                            }
                        }
                }catch (Exception $e){
                    Log::error("error", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("error.login_create_token_error_21005");
                    break;
                }
            }
            if($wechat->status == 2){   //用户状态 冻结
                $response = Lang::get('error.user_frozen_error_21002');
                break;
            }
            if($wechat->status == 0){   //用户状态 关闭
                $response = Lang::get('error.user_type_21010');
                break;
            }
            if($wechat->type == 2){     //禁止企业用户登录
                $response = Lang::get('error.user_type_21009');
                break;
            }
            //如果发现此用户是老用户，且未激活 给优惠券 且再激活
            if($wechat->type == 1 && $wechat->activate == 0){
                //注册送券
                if(Config::get("config.register_coupons") == 1){
                    $activity = Coupons::getNewUserRegister(Config::get('config.activity_id'),$response);
                    if(!is_null($activity)){
                        foreach ($activity as  $v) {
                            $coupon_base_info = Coupons::getCouponBaseInfo($v->coupon_base_info_id);
                            if (!$coupon_base_info) {
                                break;
                            }
                            if ($coupon_base_info->status == 0) {
                                break;
                            }
                            if ($coupon_base_info->date_type == 0 && strtotime($coupon_base_info->end_date.' 23:59:59') < strtotime(date('Y-m-d H:i:s', time()))) { //起止时间
                                break;
                            }
                            $coupon_whether_exist = Coupons::getCouponOther($v->coupon_base_info_id);
                            if (!is_null($coupon_whether_exist)) {
                                $coupons = Coupons::find($coupon_whether_exist->id);
                                $coupons->status = 2;
                                $coupons->received_user_id = $wechat->id;
                                $coupons->get_time = date("Y-m-d H:i:s", time());
                                if ($coupon_base_info->date_type == 1) { //顺延日期
                                    $coupons->end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
                                }
                                $coupons->save();
                                //友盟优惠券到账消息推送
                                if(Config::get('u_meng_push.is_open_u_meng_push') ==1 && Input::get('register_source_id') ==2){
                                    Orders::notifyMsg($wechat->id,2,'优惠券已到账','您的'.($coupon_base_info->amount/100).'元优惠券已到帐');
                                }
                                try {
                                    NewsLog::NewsPush($wechat->id,'',2,5,'优惠券已到账','您的'.($coupon_base_info->amount/100).'元优惠券已到帐');
                                } catch (Exception $e) {
                                    Log::error("error", array("system" => "api3.0" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                                    $response = Lang::get("error.run_exception");
//                break;
                                }
                            }
                        }
                    }
                }
                $wechat->activate = 1;
                $wechat->save();
            }
            try{
                $token="";
                $find_token = UserTokens::where('user_id',$wechat->id)->first();
                if(!is_null($find_token)){ //有token 判断token是否过期
                    if(strtotime($find_token->out_time_at) < time()){//说明过期了
                        UserTokens::where('user_id',$wechat->id)->delete();
                        $user_token = new UserTokens;
                        $user_token->user_id = $wechat->id;
                        $user_token->token = md5(Input::get('phone').time().rand(0,100));
                        $user_token->created_at = Common::num2DateTime(time());
                        $user_token->out_time_at = Common::num2DateTime(time() + Config::get("user.token_time_out"));
                        $user_token->save();
                        $token=$user_token->token;
                    }else{
                        $token=$find_token->token;
                    }
                }else{
                    $user_token = new UserTokens;
                    $user_token->user_id = $wechat->id;
                    $user_token->token = md5(Input::get('phone').time().rand(0,100));
                    $user_token->created_at = Common::num2DateTime(time());
                    $user_token->out_time_at = Common::num2DateTime(time() + Config::get("user.token_time_out"));
                    $user_token->save();
                    $token=$user_token->token;
                }

            } catch (Exception $e){
                Log::error("error", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.login_create_token_error_21005");
                break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' =>array(
                    'id'=> $wechat->id,
                    'token' => $token,
                    'phone' => $wechat->phone,
                    'real_name' => $wechat->real_name,
                    'sex' => $wechat->sex,
                    'area' => $wechat->area,
                    'remark' => $wechat->remark,
                    'type' => $wechat->type,
                    'status' =>$wechat->status,
                    'nickname' => $wechat->nickname,
                    'birthday' => $wechat->birthday,
                    'heading_img' =>  $wechat->heading_img,
                    'heading_img_url' =>  Config::get('config.heading_img_url'),
                )
            );

        } while (false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /*
    * @Author:      kc
    * @DateTime:    2017-02-24 13:50:11
    * @Description: 验证token
    */
    public function checkToken(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("wechat_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $account_user = $this->verificationUserToken(Input::get("token"),$response);
            if(is_null($account_user)){
                break;
            }
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "checkToken", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /*
       * @Author:      kc
       * @DateTime:    2017-02-23 14:10:11
       * @Description: 退出登录
     */
    public function lgout()
    {
       $validator = Validator::make(Input::all(),
           array(
               'token' => 'required',
           )
       );
        do{
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            try{
                if(Input::get('token') != 'a0311b0243f2831ce06b8fe867233767'){
                    UserTokens::where('token',Input::get('token'))->delete();
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_token_clean_error_21006");
                break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "lgout", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    public function ceshi (){
        return $this->redirect();
    }

    /*
    * @Author:      dx
    * @DateTime:    2017-05-24 13:50:11
    * @Description: 首页banner轮播
    */
    public function banner(){
        $validator = Validator::make(Input::all(),
            array(
                'source' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array());
        do{
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $bs = BannerRecords::where('status',1)->where('source',Input::get('source'))->orderBy('sort','asc')->get();
            $result = array(
                'banner_img_url' => Config::get('config.banner_img_url'),
                'banner_target_url' => Config::get('config.redirect_url'),
                'banner_arr' => $bs
            );
            $response = array( 'code' => 0,'msg' => 'ok','result' =>$result );
        }while(false);
        return json_encode($response);
    }

    /*
   * @Author:      dx
   * @DateTime:    2017-08-25 14:10:11
   * @Description: id
   */
    public function getPhone(){
        $validator = Validator::make(Input::all(),
            array(
                'userId' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("wechat_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user = Users::find(Input::get('userId'));
            if(is_null($wx_user)){
                $response = Lang::get("error.user_not_exit_21001");
                break;
            }
            $response = array( 'code' => 0,'msg' => 'ok','result' =>$wx_user );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "getPhone", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


}
